<template>
  <div class="global">
    <!-- 用户顶部搜索栏 -->
    <div style="margin-bottom: 10px">
      <el-card shadow="hover">
        <el-form
          :model="reservation"
          label-width="70px"
          ref="ruleFormRef"
          :rules="rules"
          inline="true"
        >
          <el-form-item>
            <el-input
              v-model="reservation.theme"
              size="large"
              placeholder="请输入会议主题"
              :prefix-icon="Search"
              maxlength="10"
              minlength="3"
            />
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="reservation.status"
              placeholder="请输入会议预约状态"
              size="large"
            >
              <el-option label="未开始" value="未开始" />
              <el-option label="进行中" value="进行中" />
              <el-option label="已结束" value="已结束" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="onSubmit" plain
              ><el-icon style="margin-right: 5px"><Search /></el-icon
              >搜索</el-button
            >
            <el-button type="primary" @click="reFresh" plain
              ><el-icon style="margin-right: 5px"><Refresh /></el-icon
              >重置</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div style="margin-bottom: 10px">
      <el-card
        shadow="hover"
        body-style="display: flex;"
      >
        <div style="margin-right: 20px">
          <el-button type="primary" @click="change" plain :disabled="isAdmin"
            ><el-icon style="margin-right: 3px"><Plus /></el-icon
            >新增</el-button
          >
        </div>
        <div style="margin-right: 20px">
          <el-button
            type="danger"
            :disabled="batch_delete_flag"
            @click="removeUser"
            plain
            v-if="!isAdmin"
            ><el-icon style="margin-right: 3px"><Delete /></el-icon
            >删除</el-button
          >
        </div>
        <div style="margin-right: 20px">
          <el-button type="success" @click="exportRoomData" plain :disabled="isAdmin"
            ><el-icon style="margin-right: 3px"><Download /></el-icon
            >导出</el-button
          >
        </div>
      </el-card>
    </div>

    <!-- 用户数据表格展示 -->
    <div>
      <el-table
        @selection-change="handleSelectionChange"
        :data="tableData"
        stripe
        style="width: 100%"
        height="380"
      >
        <el-table-column type="selection" width="80" />
        <el-table-column prop="theme" label="会议主题" width="150" />
        <el-table-column prop="roomName" label="会议室名" width="140" />
        <el-table-column prop="beginTime" label="会议时间" width="160" />
        <el-table-column prop="remark" label="备注" width="200" />
        <el-table-column prop="authorPhone" label="发起人" width="140" />
        <el-table-column prop="participants" label="参会人" width="120" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="scope">
            <el-button plain type="success" size="small">{{
              scope.row.status
            }}</el-button>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              plain
              type="primary"
              size="small"
              @click="updateUser(scope.row)"
              :disabled="isAdmin"
              ><el-icon><Edit /></el-icon>修改</el-button
            >
            <el-popconfirm
              title="确定要删除吗?"
              confirm-button-text="确定"
              cancel-button-text="取消"
              @confirm="confirmEvent(scope.row)"
              @cancel="cancelEvent"
            >
              <template #reference>
                <el-button plain type="danger" size="small" :disabled="isAdmin"
                  ><el-icon><Delete /></el-icon>
                  删除
                </el-button></template
              >
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>

  <!-- 用户数据搜集对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    title="新增会议"
    :center="true"
    :align-center="true"
    width="500px"
    :show-close="false"
  >
    <el-form
      :label-position="right"
      label-width="100px"
      :model="reservationFrom"
      class="el_form"
      ref="ruleFormRef"
      :rules="rules"
    >
      <el-form-item label="会议主题" prop="theme" :label-width="formLabelWidth">
        <el-input
          v-model="reservationFrom.theme"
          size="large"
          placeholder="请输入会议主题"
        />
      </el-form-item>
      <el-form-item
        label="开始时间"
        prop="beginTime"
        :label-width="formLabelWidth"
      >
        <el-date-picker
          v-model="reservationFrom.beginEndTime"
          type="datetimerange"
          range-separator="到"
          format="YYYY-MM-DD HH:mm"
          value-format="YYYY-MM-DD H:m"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        />
      </el-form-item>
      <el-form-item
        label="发起人"
        prop="authorPhone"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="reservationFrom.authorPhone"
          :rows="3"
          size="large"
          placeholder="请输入会议发起人号码"
          maxlength="11"
          minlength="11"
        />
      </el-form-item>
      <el-form-item
        label="参会人"
        prop="participants"
        :label-width="formLabelWidth"
      >
        <el-input
          v-model="reservationFrom.participants"
          :rows="3"
          size="large"
          placeholder="请选择参会人"
          @click="open"
        />
      </el-form-item>
      <el-form-item
        label="会议室"
        prop="roomName"
        :label-width="formLabelWidth"
      >
        <el-select
          size="large"
          v-model="reservationFrom.roomName"
          clearable
          placeholder="请选择会议室"
        >
          <el-option
            v-for="item in roomNames"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
        <el-input
          v-model="reservationFrom.remark"
          type="textarea"
          :rows="3"
          placeholder="备注内容，最长100字"
          maxlength="100"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog_footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveRoom"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 分页部分 -->
  <div class="pagenation">
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="sizes, prev, pager, next"
      :total="total"
      prev-text="第"
      next-text="页"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 弹出层 -->
  <div>
    <el-drawer v-model="drawer" title="通过部门查询" size="50%">
      <div>
        <el-dropdown>
          <span class="el-dropdown-link">
            部门选择
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu
              v-for="(item, index) in depts"
              :key="index"
              @click="innerOpen(item)"
            >
              <el-dropdown-item>{{ item }}</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-drawer
          v-model="innerDrawer"
          title="组内成员"
          :append-to-body="true"
          :before-close="handleClose"
        >
          <div v-for="(item, index) in deptNumbers" :key="index">
            <el-checkbox
              :label="item.name"
              size="large"
              border
              @click="checked(item.phone)"
            />
          </div>
        </el-drawer>
      </div>
    </el-drawer>
  </div>
</template>
      
    <script setup>
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import {
  Search,
  Refresh,
  Edit,
  Delete,
  Plus,
  Download,
} from "@element-plus/icons-vue";
import {
  list,
  save,
  getReservationById,
  removeById,
  update,
  getMeetRoomData,
  getDeptName,
  getdeptNumbers,
} from "@/api/reservation";
import { useTokenStore } from "@/stores/token";
const TokenStore = useTokenStore();

///////////////////////////////////////////////////////////////////数据区
const tableData = ref([]);
const pageNo = ref(1);
const pageSize = ref(10);
const total = ref(0);
const dialogFormVisible = ref(false);
const ids = ref([]);
const batch_delete_flag = ref(true);
const roomNames = ref([]);
//模糊查询数据
const reservation = ref({
  theme: "",
  status: "",
});
//保存用户
const reservationFrom = ref({
  id: null,
  theme: "",
  beginEndTime: [], //会议开始时间
  authorPhone: "", //发起人号码
  participants: [], //参会人
  roomName: "", // 会议室
  remark: "", //会议备注
});

///////////////////////////////////////////////////////////////////////////方法区
//异步获取用户分页数据
//检测是否是测试账号
const isAdmin = ref(false)
onMounted(async () => {
  //检测是否是测试账号
  isAdmin.value = TokenStore.isAdmin;
  const res = await list(pageNo.value, pageSize.value, reservation.value);
  if (res.code === 200) {
    if (res.data === null) {
      tableData.value = null;
    } else {
      tableData.value = res.data.records;
      total.value = res.data.total;
    }
  }
  await getMeetRoomNames();
});

//异步获取用户分页数据
async function initList() {
  await list(pageNo.value, pageSize.value, reservation.value).then((res) => {
    if (res.code === 200) {
      if (res.data === null) {
        tableData.value = null;
      } else {
        tableData.value = res.data.records;
        total.value = res.data.total;
      }
    }
  });
}

//异步获取会议室名称数据
async function getMeetRoomNames() {
  await getMeetRoomData().then((res) => {
    if (res.code === 200) {
      roomNames.value = res.data;
      console.log(roomNames.value);
    }
  });
}

//重置
async function reFresh() {
  if (
    reservation.value.theme != "" ||
    reservation.value.authorPhone != "" ||
    reservation.value.status != ""
  ) {
    reservation.value.theme = "";
    reservation.value.authorPhone = "";
    reservation.value.status = "";
    initList();
  }
}

//搜索
async function onSubmit() {
  if (
    reservation.value.theme != "" ||
    reservation.value.authorPhone != "" ||
    reservation.value.status != ""
  ) {
    initList();
  }
}

//新增用户弹框
function change() {
  dialogFormVisible.value = !dialogFormVisible.value;
}

//表单校验
const ruleFormRef = ref(null);
// 校验规则
const rules = {
  theme: [{ required: true, message: "请输入会议主题", trigger: "blur" }],
  beginTime: [
    { required: true, message: "请输入会议开始时间", trigger: "blur" },
  ],
  meetLength: [{ required: true, message: "请输入会议时长", trigger: "blur" }],
  authorPhone: [
    { required: true, message: "请输入会议发起人号码", trigger: "blur" },
  ],
  participants: [
    { required: true, message: "请选择会议参会人号码", trigger: "change" },
  ],
  roomName: [{ required: true, message: "请选择会议室", trigger: "change" }],
};

//新增 / 修改 用户
function saveRoom() {
  //表单校验
  ruleFormRef.value.validate((valid) => {
    if (valid) {
      if (!reservationFrom.value.id) {
        console.log(reservationFrom.value);
        //新增用户
        save(reservationFrom.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "保存成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      } else {
        //修改用户
        update(reservationFrom.value).then((res) => {
          if (res.code === 200) {
            ElMessage({
              showClose: true,
              message: "修改成功！",
              type: "success",
            });
            //异步请求用户分页数据
            initList();
          }
        });
      }
      dialogFormVisible.value = false;
      cancel();
    }
  });
}

//取消
function cancel() {
  reservationFrom.value.theme = "";
  reservationFrom.value.authorPhone = "";
  reservationFrom.value.roomName = "";
  reservationFrom.value.participants = [];
  reservationFrom.value.remark = "";
  reservationFrom.value.meetLength = "";
  reservationFrom.value.beginEndTime = [];
  dialogFormVisible.value = false;
}

//修改用户：回显用户数据
function updateUser(row) {
  if (row.status == 0) {
    ElMessage({
      showClose: true,
      message: "会议处于审核通过状态，请先撤销！",
      type: "warning",
    });
  } else {
    getReservationById(row.id).then((res) => {
      if (res.code === 200) {
        reservationFrom.value = res.data;
        dialogFormVisible.value = true;
      }
    });
  }
}

//批量删除用户
function removeUser() {
  //批量删除
  removeById(ids.value).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  if (ids.value.length > 0) {
    batch_delete_flag.value = false;
  }
  if (ids.value.length === 0) {
    batch_delete_flag.value = true;
  }
}

//pageSize改变时
function handleSizeChange(value) {
  pageSize.value = value;
  initList();
}

//pageNo改变时
function handleCurrentChange(value) {
  pageNo.value = value;
  initList();
}

//单个删除用户
function confirmEvent(row) {
  removeById(row.id).then((res) => {
    if (res.code === 200) {
      ElMessage({
        showClose: true,
        message: "删除成功！",
        type: "success",
      });
      //异步请求用户分页数据
      initList();
    }
  });
}

//取消删除用户
function cancelEvent() {
  ElMessage({
    showClose: true,
    message: "取消删除！",
    type: "warning",
  });
}

//用户数据导出
function exportRoomData() {
  window.open("https://www.sixkey-world.top:8600/common/reservationExport");
  ElMessage({
    showClose: true,
    message: "导出成功！",
    type: "success",
  });
}

const drawer = ref(false);
const depts = ref([]);
function open() {
  drawer.value = true;
  getDeptName().then((res) => {
    if (res.code === 200) {
      depts.value = res.data;
    }
  });
}

const innerDrawer = ref(false);
const deptNumbers = ref([]);
function innerOpen(deptName) {
  getdeptNumbers(deptName).then((res) => {
    if (res.code === 200) {
      deptNumbers.value = res.data;
      console.log(deptNumbers.value);
    }
  });
  innerDrawer.value = true;
}

function checked(phone) {
  if (reservationFrom.value.participants.indexOf(phone) === -1) {
    //做数据去重
    reservationFrom.value.participants.push(phone);
  }
}
</script>
    
    <style scoped>
.global {
  padding-top: 10px;
  padding-left: 10px;
  padding-right: 10px;
  background-color: #f5f5f5;
}
.pagenation {
  margin-top: 15px;
  margin-left: 500px;
}

.el-input {
  width: 260px;
}

.el_form {
  margin-top: 10px;
  margin-left: 20px;
}

.dialog_footer {
  margin-left: 260px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 0;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  text-align: center;
}

.avatar-uploader .avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>  